<style lang="scss" scoped src="./style.scss">

</style>

<template>
    <div class="post-edit-page padding-l-16 padding-r-16 padding-b-16 edit-form">
        <div class="bread-crumb">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: '/posts' }">文档管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{modeName}}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-row :gutter="8">
            <el-col :xs="24" :sm="16" :md="16" :lg="17" :xl="17">
                <div cw-role="cell" cw-valign="middle">
                    <div cw-role="cell" class="w120 edit-title">文章标题：</div>
                    <div cw-role="cell" cw-layout="fit">
                        <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
                    </div>
                    <div cw-role="cell" class="margin-l-8 bg-white">
                        <el-color-picker v-model="form.title_color"></el-color-picker>
                    </div>
                </div>
                <div class="post-edit-content" id="postEditContent">
                    <div class="edit-title">文章内容：</div>
                    <tinymce v-show="!loading" ref="contentEditor" id="d1" v-model="form.content" :toolbar1="mceToolbar1" :plugins="mcePlugins" :other_options="mceOption"></tinymce>
                </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8" :lg="7" :xl="7">
                <div cw-role="cell" cw-mode="x-equal" class="margin-b-16">
                    <el-button cw-role="cell" cw-align="center" type="primary" @click="submit">{{publishBtn}}</el-button>
                    <el-button cw-role="cell" cw-align="center">预览</el-button>
                </div>
                <div class="edit-form-card">
                    <div class="edit-form-card-head edit-title">文章封面图</div>
                    <div class="edit-form-card-content padding-8">
                        <div cw-role="cell" cw-align="center" cw-valign="middle" class="edit-thumb" @click="thumbDialogVisible = true" :style="editThumbStyle">
                            <div cw-role="cell" cw-mode="y" cw-align="center" cw-valign="middle" v-if="form.thumb" class="edit-thumb-mask">
                                <i class="ion ion-edit"></i>
                                <span>更换或预览封面图</span>
                            </div>
                            <div cw-role="cell" cw-mode="y" cw-align="center" cw-valign="middle" v-else class="no-thumb">
                                <i class="ion ion-plus"></i>
                                <span>添加封面图</span>
                            </div>
                        </div>
                    </div>
                    <el-dialog title="上传文章封面图" :visible.sync="thumbDialogVisible" width="400px">
                        <croppa v-model="postThumb" :width="360" :height="240" :initial-image="thumbUrl" :prevent-white-space="true" :disable-drag-and-drop="true" placeholder="选择要上传的图片"></croppa>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="thumbDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="uploadThumb">确 定</el-button>
                        </span>
                    </el-dialog>
                </div>
                <div class="edit-form-card">
                    <div class="edit-form-card-head edit-title">选择文章分类</div>
                    <div class="edit-form-card-content">
                        <cats-select ref="catsSelect" :cats-data="categoryData" v-model="form.category" :change="onSelectCats" style="display:block"></cats-select>
                    </div>
                </div>
                <div class="edit-form-card">
                    <el-tabs v-model="activeName" class=" padding-l-16 padding-r-16 padding-b-16">
                        <el-tab-pane label="关键词" name="keywords" class="keywords-tag">
                            <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="delTag(tag)">
                                {{tag}}
                            </el-tag>
                            <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showTagInput">+ 新关键词</el-button>
                        </el-tab-pane>
                        <el-tab-pane label="描述" name="description">
                            <el-input type="textarea" :rows="6" v-model="form.description" placeholder="请输入文章描述"></el-input>
                        </el-tab-pane>
                        <el-tab-pane label="设置发布时间" name="setTime">
                            <el-date-picker v-model="form.update_time" type="date" placeholder="选择发布日期">
                            </el-date-picker>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import Vue from 'vue';
import tinymce from '@/modules/plugins/vue-tinymce-editor';
import Croppa from 'vue-croppa';
import 'vue-croppa/dist/vue-croppa.css';
import catsSelect from '@/modules/plugins/cats-select/index.vue';

Vue.component('tinymce', tinymce);
Vue.component('croppa', Croppa.component);
/*
    global globalVar
*/

export default {
    name: 'postEdit',
    data() {
        return {
            loading: false,
            id: parseInt(this.$route.params.id, 10),
            form: {
                title: '',
                title_color: null,
                thumb: '',
                content: '',
                category: 0,
                description: '',
                update_time: new Date(),
                keywords: ''
            },
            mceToolbar1:
                'undo redo | formatselect | bold italic strikethrough forecolor backcolor | link image | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat | fullscreen',
            mcePlugins: [
                'advlist autolink lists link image charmap print preview hr anchor pagebreak',
                'searchreplace wordcount visualblocks visualchars code fullscreen',
                'insertdatetime media nonbreaking save table contextmenu directionality',
                'template imagetools'
            ],
            mceOption: {
                fixed_toolbar_container: '#postEditContent',
                height: '500',
                language_url: '/venders/tinymce/langs/zh_CN.js',
                image_title: true,
                automatic_uploads: true,
                file_picker_types: 'image',
                file_picker_callback: function(cb, value, meta) {
                    var input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    input.setAttribute('accept', 'image/*');

                    input.onchange = function() {
                        var file = this.files[0];

                        var reader = new window.FileReader();
                        reader.onload = function() {
                            var id = 'blobid' + new Date().getTime();
                            var blobCache =
                                tinymce.activeEditor.editorUpload.blobCache;
                            var base64 = reader.result.split(',')[1];
                            var blobInfo = blobCache.create(id, file, base64);
                            blobCache.add(blobInfo);

                            cb(blobInfo.blobUri(), { title: file.name });
                        };
                        reader.readAsDataURL(file);
                    };

                    input.click();
                }
            },
            postThumb: null,
            thumbDialogVisible: false,
            categoryData: [],
            categorySelect: [],
            categoryObj: {},
            categoryTree: [],
            activeName: 'keywords',
            dynamicTags: [],
            inputVisible: false,
            inputValue: ''
        };
    },
    computed: {
        modeName() {
            return this.$route.params.id === 'add' ? '新增文章' : '编辑文章';
        },
        publishBtn() {
            return this.$route.params.id === 'add' ? '发布' : '保存';
        },
        thumbUrl() {
            return this.form.thumb
                ? globalVar.uploadUrl + this.form.thumb
                : null;
        },
        editThumbStyle() {
            if (this.form.thumb) {
                return {
                    'background-image': 'url(' + this.thumbUrl + ')',
                    'background-size': 'cover'
                };
            } else {
                return {};
            }
        }
    },
    methods: {
        getData() {
            this.loading = true;
            return this.whaleXHR
                .GET('/posts/' + this.$route.params.id)
                .then(res => {
                    this.loading = false;
                    if (res.code === 'success') {
                        console.log(res.data);
                        this.form = res.data;
                        this.dynamicTags = this.form.keywords
                            ? this.form.keywords.split(',')
                            : [];
                        return res;
                    }
                });
        },
        uploadThumb() {
            if (!this.postThumb.hasImage()) {
                this.$message({
                    message: '请选择需要上传的图片',
                    type: 'warning'
                });
                return;
            }

            this.postThumb.generateBlob(
                blob => {
                    var fd = new FormData();
                    fd.append('file', blob, 'xx.jpg');
                    console.log(blob);
                    this.whaleXHR.POST('/common/picUpload', fd).then(res => {
                        console.log(res);
                        if (res.code === 'success') {
                            this.thumbDialogVisible = false;
                            this.form.thumb = res.data.url;
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                    // write code to upload the cropped image file (a file is a blob)
                },
                'image/jpeg',
                0.8
            );
        },
        getCats() {
            this.whaleXHR.GET('/category').then(res => {
                if (res.code === 'success') {
                    this.$refs.catsSelect.init(res.data);
                }
            });
        },
        onSelectCats(value) {
            this.form.category = value;
        },
        delTag(tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
            this.form.keywords = this.dynamicTags.join(',');
        },
        showTagInput() {
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm() {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.dynamicTags.push(inputValue);
                this.form.keywords = this.dynamicTags.join(',');
            }
            this.inputVisible = false;
            this.inputValue = '';
        },
        submit() {
            if (!this.form.title) {
                this.$message({
                    message: '请填写文章标题',
                    type: 'error'
                });
                return;
            }

            if (!this.form.content) {
                this.$message({
                    message: '请填写文章内容',
                    type: 'error'
                });
                return;
            }

            let successFn = (code, text) => {
                if (code === 'success') {
                    this.$message({
                        message: text + '成功！',
                        duration: 1000,
                        onClose: () => {
                            this.$router.push('/posts');
                        },
                        type: 'success'
                    });
                }
            };

            if (this.id) {
                this.whaleXHR.PUT('/posts/' + this.id, this.form).then(res => {
                    successFn(res.code, '编辑');
                });
            } else {
                this.whaleXHR.POST('/posts', this.form).then(res => {
                    successFn(res.code, '添加');
                });
            }
        },
        resetForm() {
            this.form = {
                title: '',
                title_color: null,
                thumb: '',
                content: '',
                category: 0,
                description: '',
                update_time: new Date(),
                keywords: ''
            };
            this.dynamicTags = [];
        },
        initMce() {
            this.$refs.contentEditor.init();
        }
    },
    mounted() {
        if (this.id && this.$route.params.id !== 'add') {
            this.getData().then(res => {
                this.getCats();
                this.initMce();
            });
        } else {
            this.getCats();
            this.initMce();
        }
    },
    beforeRouteEnter: (to, from, next) => {
        let id = parseInt(to.params.id, 10);
        if (!id && to.params.id !== 'add') {
            next('/posts');
        } else {
            next();
        }
    },
    beforeRouteUpdate(to, from, next) {
        let id = parseInt(to.params.id, 10);
        if (!id && to.params.id !== 'add') {
            next('/posts');
        } else {
            this.resetForm();
            this.id = id;
            next();
        }
    },
    components: {
        catsSelect
    }
};
</script>
